package com.yzt.message;

import android.content.Context;
import android.net.Uri;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.user.GroupProfileBase;
import com.yzt.zhuju.network.entity.user.GroupProfileList;
import com.yzt.zhuju.network.entity.user.UserProfileList;
import com.yzt.message.common.ThreadManager;
import com.yzt.message.util.MessageInfoUtil;
import com.yzt.plugin_imageloader.ImageLoadUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

import io.rong.imkit.RongIM;
import io.rong.imkit.userinfo.RongUserInfoManager;
import io.rong.imkit.userinfo.UserDataProvider;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.UserInfo;

public class IMInfoProvider {

    public IMInfoProvider() {

    }

    public void init(Context context) {
        initTask(context);
        initInfoProvider();
        initData();
    }

    /**
     * 初始化同步数据时使用的任务对象
     */
    private void initTask(Context context) {

    }

    /**
     * 初始化信息提供者，包括用户信息，群组信息，群主成员信息
     */
    private void initInfoProvider() {
        RongUserInfoManager.getInstance().setUserInfoProvider(new UserDataProvider.UserInfoProvider() {
            @Override
            public UserInfo getUserInfo(String userId) {
                Log.e("wang", "setUserInfoProvider1----->" + userId);
                // 更新用户信息
                updateUserInfo(userId);
                return null;
            }
        }, true);
    }

    private void initData() {

    }

    static CopyOnWriteArraySet<String> copyOnWriteArrayList = new CopyOnWriteArraySet<>();

    /**
     * 更新用户信息
     */
    public static void updateUserInfo(String mTargetId) {
        if (MessageInfoUtil.isNeedFilter(mTargetId)) {
            return;
        }
        copyOnWriteArrayList.add(mTargetId);
        ThreadManager.getInstance().removeCallbacks(runnable);
        ThreadManager.getInstance().runOnUIThreadDelayed(runnable, 500);
    }

    static Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Object[] uids = copyOnWriteArrayList.toArray();

            copyOnWriteArrayList.clear();

            int size = uids.length;

            if (size == 0) {
                return;
            }
            // int count = (int) Math.ceil(size * 1.0f / 100);
            if (size == 1) {
                if (uids[0].toString().length() > 10) {
                    loadGroupProfileList(uids);
                } else {
                    loadUserProfileList(uids);
                }
            } else {
                for (Object uid : uids) {
//                    int begin = 100 * i;
//                    int end = 100 + 100 * i;
//                    if (i == count - 1) {
//                        end = size;
//                    }
//                    Object[] array = new Object[end - begin];
//                    System.arraycopy(uids, 0, array, 0, end - begin);
//                    loadUserProfileList(array);
                    if (uid.toString().length() > 10) {
                        loadGroupProfileList(uids);
                    } else {
                        loadUserProfileList(uids);
                    }
                }
            }
        }
    };

    /**
     * 刷新用户信息
     *
     * @param userId 用户ID
     */
    private static void loadUserProfileList(Object[] userId) {

        BizLayer.getInstance().getAccountModule().loadUserProfileList(userId, new AresSubscriber<UserProfileList>() {
            @Override
            protected void onSuccess(UserProfileList userProfileList) {

                if (userProfileList == null || userProfileList.getUsers() == null || userProfileList.getUsers().isEmpty()) {
                    return;
                }

                for (UserProfileList.ListDTO listDTO : userProfileList.getUsers()) {
                    try {
                        IMManager.getInstance().updateUserInfoCache(listDTO.getUserId(), listDTO.getNickName(),
                                Uri.parse(ImageLoadUtil.url2webp(listDTO.getAvatar(), 150)));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    /**
     * 刷新群组信息
     */
    private static void loadGroupProfileList(Object[] groupId) {
//        List<String> list = new ArrayList<>();
//        for (Object uid : groupId) {
//            list.add(uid.toString());
//        }
//        BizLayer.getInstance().getAccountModule().loadGroupProfileList(list, new AresSubscriber<GroupProfileBase>() {
//            @Override
//            protected void onSuccess(GroupProfileBase userProfileList) {
//
//                if (userProfileList == null || userProfileList.getList() == null || userProfileList.getList().isEmpty()) {
//                    return;
//                }
//
//                for (GroupProfileList listDTO : userProfileList.getList()) {
//                    try {
//                        String groupInfo = JSON.toJSONString(listDTO.getGroupMembers());
//                        Group group = new Group(listDTO.getGroupId(), listDTO.getGroupName(), Uri.parse(groupInfo));
//                        RongIM.getInstance().setMessageAttachedUserInfo(true);
//                        RongIM.getInstance().refreshGroupInfoCache(group);
//                        Log.e("wang", "refreshUserInfoCache-------------" + JSON.toJSONString(group));
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        });
    }
}